1
|
|
|
import {ModelInterface, ModelStaticInterface} from "../JeloquentInterfaces"; |
2
|
|
|
import Table from "./Table"; |
3
|
|
|
|
4
|
|
|
export default class Database { |
5
|
|
|
|
6
|
|
|
private _name: string; |
7
|
|
|
|
8
|
|
|
private _tables: Map<string, Table>; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* |
12
|
|
|
* @param name |
13
|
|
|
* @param models |
14
|
|
|
*/ |
15
|
|
|
constructor(name, models:Array<ModelStaticInterface>) { |
16
|
|
|
this._name = name; |
17
|
|
|
this._tables = new Map(); |
18
|
|
|
|
19
|
|
|
models.forEach((model: ModelStaticInterface) => { |
20
|
|
|
this.register(model); |
21
|
|
|
}); |
22
|
|
|
} |
23
|
|
|
|
24
|
|
|
get name(): string { |
25
|
|
|
return this._name; |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
addIndex(table:string, indexName:string, lookUpKey:string, id:string|number): void { |
29
|
|
|
this.table(table).addIndex(indexName, lookUpKey, id) |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
allModels(table): Map<string|number, ModelInterface> { |
33
|
|
|
return this.table(table).allModels(); |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
drop(table: string): void { |
37
|
|
|
this._tables.delete(table); |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
ids(table: string): Array<string|number> { |
41
|
|
|
return this.table(table).ids; |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
indexes(table: string): Map<string, Map<string|number, Set<string|number>>> { |
45
|
|
|
return this.table(table).indexes; |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* @todo Build better way of parsing queries; |
50
|
|
|
*/ |
51
|
|
|
query(sql) { |
52
|
|
|
const sqlParts = sql.match(/^((SELECT)|(INSERT)|(DELETE))\s+(.*)\s+FROM\s+([^\s]+)(\s+WHERE\s+([^\s]+)\s+(=)\s+([^\s+]))?((\s+)|;)?$/i); |
53
|
|
|
|
54
|
|
|
if (sqlParts.length === 0) { |
55
|
|
|
return null; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
const action = sqlParts[1]; |
59
|
|
|
//const fields = sqlParts[5].split(','); |
60
|
|
|
const table = sqlParts[6] |
61
|
|
|
const matchField = sqlParts[8]; |
62
|
|
|
const matchValue = sqlParts[10]; |
63
|
|
|
|
64
|
|
|
if (matchField === 'id') { |
65
|
|
|
return this.table(table)[action.toLowerCase()](matchValue); |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
if (matchField === undefined && action === 'SELECT') { |
69
|
|
|
return this.table(table).all(); |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
return null; |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
register(model: ModelStaticInterface) { |
76
|
|
|
const table = new Table(model); |
77
|
|
|
this._tables.set(table.name, table); |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
setIndexes(): void { |
81
|
|
|
this._tables.forEach((table) => { |
82
|
|
|
table.setupIndexes(); |
83
|
|
|
}); |
84
|
|
|
} |
85
|
|
|
|
86
|
|
|
showTables(): Array<string> { |
87
|
|
|
return [...this._tables.keys()]; |
88
|
|
|
} |
89
|
|
|
|
90
|
|
|
table(name:string): Table { |
91
|
|
|
return this._tables.get(name); |
92
|
|
|
} |
93
|
|
|
} |